<template>
  <div>
    <!-- 提示消息 -->
    <el-card>
      <div>
        <span style="color:red">“重点客户”</span>更新时间最少
        <span style="color:red">一周一次</span>，
        <span style="color:red">“中等”</span>更新时间最少
        <span style="color:red">半月一次</span>，
        <span style="color:red">“一般”</span>更新时间最少
        <span style="color:red">一月一次</span>, 最新跟进情况
        <span style="color:red">未更新则标识红色</span>；续签跟进在
        <span style="color:red">维保到期前3个月</span>即可开始跟踪，
        <span style="color:#67C23A;">绿色标识</span>提醒可开始续签跟踪
      </div>
      <div>
        <el-button size="small"
                   @click="onExplain">(成熟度/跟踪等级说明)</el-button>
      </div>
    </el-card>
    <!-- 搜索 -->
    <v-page-search>
      <el-form :inline="true"
               :model="searchForm"
               solt="search-from">
        <el-form-item>
          <el-input v-model="searchForm.area"
                    placeholder="行政区划"
                    style="width: 120px"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="searchForm.customerName"
                    placeholder="客户单位"
                    style="width: 120px"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="searchForm.contractId"
                    placeholder="合同号"
                    style="width: 120px"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="searchForm.contractName"
                    placeholder="项目名称"
                    style="width: 180px"></el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.territory"
                     multiple
                     collapse-tags
                     style="width: 170px"
                     placeholder="责任区域">
            <el-option v-for="item in options.territory"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.primaryTerritory"
                     multiple
                     collapse-tags
                     style="width: 170px"
                     placeholder="主跟小组">
            <el-option v-for="item in options.primaryTerritory"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input v-model="searchForm.trackPepole"
                    placeholder="主跟进人"
                    style="width: 120px"></el-input>
        </el-form-item>
        <el-form-item>
          <el-date-picker v-model.trim="searchForm.contractDate"
                          type="month"
                          placeholder="计划签订"
                          style="width: 120px">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.advancingState"
                     multiple
                     collapse-tags
                     style="width: 140px"
                     placeholder="推进">
            <el-option v-for="item in options.advancingState"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.projectMaturity"
                     multiple
                     collapse-tags
                     style="width: 150px"
                     placeholder="成熟度">
            <el-option v-for="item in options.projectMaturity"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.projectLevel"
                     multiple
                     collapse-tags
                     style="width: 150px"
                     placeholder="跟踪等级">
            <el-option v-for="item in options.projectLevel"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.contractDirection"
                     multiple
                     collapse-tags
                     style="width: 150px"
                     placeholder="类型方向">
            <el-option v-for="item in options.contractDirection"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.signType"
                     collapse-tags
                     style="width: 150px"
                     placeholder="签订类型">
            <el-option v-for="item in options.signType"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input v-model.number="searchForm.estimatedAmount"
                    placeholder="预估金额"
                    style="width: 120px"></el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.isAdvancingState"
                     clearable
                     style="width: 120px"
                     placeholder="待跟踪">
            <el-option v-for="item in options.isAdvancingState"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.isEnable"
                     clearable
                     style="width: 120px"
                     placeholder="是否在跟">
            <el-option v-for="item in options.isEnable"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="search-but">
        <el-button size="small"
                   type="primary"
                   icon="el-icon-search"
                   @click="search">搜索</el-button>
        <el-button size="small"
                   type="info"
                   icon="el-icon-delete"
                   @click="clearCondition">清除</el-button>
        <el-button size="small"
                   icon="el-icon-plus"
                   @click="addProject">添加</el-button>
        <el-button size="small"
                   type="warning"
                   icon="el-icon-document"
                   v-loading="exprotLoading"
                   @click="exprotProjectInfo">导出</el-button>
      </div>
    </v-page-search>
    <!-- 列表 -->
    <el-table :data="tableData"
              @row-dblclick="editProject"
              v-loading="loading"
              show-summary
              border
              stripe>
      <el-table-column type="expand"
                       size="small"
                       width="40">
        <template slot-scope="props"
                  size="small">
          <el-form label-position="left"
                   class="demo-table-expand">
            <el-form-item label="原合同号:">
              <span>{{ props.row.contractId }}</span>
            </el-form-item>
            <el-form-item label="新合同号:">
              <span>{{ props.row.newContractId }}</span>
            </el-form-item>
            <el-form-item label="签订类型:">
              <span>{{ props.row.signType }}</span>
            </el-form-item>
            <el-form-item label="签订人员:">
              <span>{{ props.row.contractingOfficer }}</span>
            </el-form-item>
            <el-form-item label="签订金额:">
              <span>{{ props.row.signAmount+'元' }}</span>
            </el-form-item>
            <el-form-item label="跟踪记录:">
              <span>{{ props.row.content }}</span>
            </el-form-item>
            <el-form-item label="失败原因:">
              <span>{{ props.row.causeFailure }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column prop="territory"
                       label="责任区域"
                       sortable
                       align="center"
                       width="85" />
      <el-table-column prop="province"
                       label="省"
                       sortable
                       align="center"
                       width="65" />
      <el-table-column prop="city"
                       label="市"
                       sortable
                       align="center"
                       width="65" />
      <el-table-column prop="county"
                       label="县"
                       sortable
                       align="center"
                       width="65" />
      <el-table-column prop="customerName"
                       label="客户单位"
                       sortable
                       align="center"
                       width="85">
        <template slot-scope="props">
          <el-popover placement="bottom"
                      trigger="hover"
                      :content="props.row.customerName">
            <span slot="reference"
                  class="table-overflow-hidden">{{props.row.customerName}}</span>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="contractName"
                       label="项目名称"
                       sortable
                       align="center"
                       width="120">
        <template slot-scope="props">
          <el-popover placement="bottom"
                      trigger="hover"
                      :content="props.row.contractName">
            <span slot="reference"
                  class="table-overflow-hidden">{{props.row.contractName}}</span>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="primaryTerritory"
                       label="主跟进组"
                       sortable
                       align="center"
                       width="85" />
      <el-table-column prop="contractType"
                       label="分布"
                       align="center"
                       width="50" />
      <el-table-column prop="projectMaturity"
                       label="成熟度"
                       sortable
                       align="center"
                       width="75" />
      <el-table-column prop="estimatedAmount"
                       label="预估金额"
                       sortable
                       align="center"
                       width="85" />
      <el-table-column prop="signAmount"
                       label="签订金额"
                       sortable
                       align="center"
                       width="85"
                       v-if="searchForm.projectMaturity.indexOf('已签') !==-1 ? true : false" />
      <el-table-column prop="projectLevel"
                       label="跟踪等级"
                       sortable
                       align="center"
                       width="90">
        <template slot-scope="props">
          <!-- <el-button type="danger"
                     size="mini"
                     v-if="renderProjectLevel(props.row)">{{ props.row.projectLevel }}</el-button> -->
          <span :class="{'table-background-color-success' : renderProjectLevel(props.row) }">{{ props.row.projectLevel }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="contractDate"
                       label="计划签订"
                       sortable
                       align="center"
                       width="90" />
      <el-table-column prop="trackPepole"
                       label="主跟进人"
                       sortable
                       align="center"
                       width="85" />
      <el-table-column prop="tm"
                       label="跟进时间"
                       sortable
                       align="center"
                       width="100">
        <template slot-scope="props">
          <!-- <el-button type="danger"
                     size="mini"
                     v-if="renderTm(props.row)">{{ props.row.tm }}</el-button> -->
          <span :class="{'table-background-color-red' : renderTm(props.row)}">{{ props.row.tm }}</span>
        </template>
      </el-table-column>
      <el-table-column label="跟踪情况"
                       sortable
                       header-align="center"
                       min-width="100">
        <template slot-scope="props">
          <el-popover placement="bottom"
                      trigger="hover"
                      :content="props.row.content">
            <span slot="reference"
                  class="table-overflow-hidden">{{props.row.content}}</span>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="操作"
                       width="50"
                       align="center"
                       v-if="userInfo.isEdit">
        <template slot-scope="scope">
          <el-button type="text"
                     size="mini"
                     @click="delProjectInfo(scope.row.contractId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination layout="total, sizes, prev, pager, next, jumper"
                   :total="pagging.total"
                   :current-page="pagging.currentPage"
                   :page-sizes="pagging.sizes"
                   @size-change="sizeChange"
                   @current-change="pageChange">
    </el-pagination>
    <!-- 项目信息 -->
    <trace-dailog @close-dialog="onClose"></trace-dailog>
    <!-- 说明信息 -->
    <explain :explain-dialog-visible="explainDialogVisible"
             @close="onCloseExplain"></explain>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import _ from 'lodash'
import Bus from '@/utils/bus'
import Moment from 'moment'
import { getMLists, delMInfoContractId, exprotMInfo } from '@/api/maintenance'
import TraceDailog from './detail/trace-dailog'
import PopoverView from './plant/popover-view-completed'
import Explain from './explain/explain'

export default {
  data() {
    return {
      loading: false,
      exprotLoading: false,
      dialogVisible: false,
      explainDialogVisible: false,
      // 筛选条件
      searchForm: {
        area: '',
        customerName: '',
        contractId: '',
        contractName: '',
        territory: [],
        primaryTerritory: [],
        advancingState: ['是'],
        trackPepole: '',
        contractDate: '',
        projectMaturity: [],
        projectLevel: [],
        signType: '',
        estimatedAmount: null,
        contractDirection: [],
        isAdvancingState: '',
        isEnable: '是'
      },
      // 选项
      options: {
        // 主跟进组
        primaryTerritory: [],
        // 责任区域
        territory: [],
        // 签订类型
        signType: [],
        // 成熟度
        projectMaturity: [],
        // 推进
        advancingState: [],
        // 跟踪等级
        projectLevel: [],
        // 方向
        contractDirection: [],
        // 是否待跟踪
        isAdvancingState: [
          {
            value: '是',
            label: '是'
          },
          {
            value: null,
            label: '否'
          }
        ],
        isEnable: [
          {
            value: '是',
            label: '是'
          },
          {
            value: null,
            label: '否'
          }
        ]
      },
      // 表格数据
      tableData: [],
      // 分页属性
      pagging: {
        total: 0,
        currentPage: 1,
        pageSize: 50,
        sizes: [50, 100, 300, 500, 1000]
      }
    }
  },
  computed: {
    ...mapGetters([
      'userInfo',
      'appEnum'
    ])
  },
  mounted() {
    this.initEnum()
  },
  methods: {
    search() {
      this.pagging.currentPage = 1
      this.getTableData()
    },
    // 请求服务合同列表数据
    getTableData() {
      this.loading = true
      const params = _.assignIn({}, this.searchForm, {
        pageIndex: this.pagging.currentPage,
        pageSize: this.pagging.pageSize
      })
      // 多选条件处理
      params.territory = params.territory.join(',')
      params.advancingState = params.advancingState.join(',')
      params.projectMaturity = params.projectMaturity.join(',')
      params.projectLevel = params.projectLevel.join(',')
      params.primaryTerritory = params.primaryTerritory.join(',')
      params.contractDirection = params.contractDirection.join(',')

      if (params.contractDate !== '' && params.contractDate !== null) params.contractDate = Moment(params.contractDate).format('YYYY-MM')

      // 请求数据
      getMLists(params).then(res => {
        if (res.data.success) {
          const result = res.data.data
          this.tableData = result.data
          this.pagging.total = result.totalCount
          this.pagging.currentPage = result.pageIndex
          this.pagging.pageSize = result.pageSize
          this.loading = false
        }
      })
    },
    // 删除服务合同
    delProjectInfo(contractId) {
      this.$confirm('此操作将永久删除该合同信息与相关记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false
      }).then(() => {
        delMInfoContractId({
          contractId: contractId
        }).then(res => {
          if (res.data.success) {
            const result = res.data.data
            if (result) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.getTableData()
            }
          }
        })
      })
    },
    // 每页显示条数变更新
    sizeChange(size) {
      this.pagging.pageSize = size
      this.getTableData()
    },
    // 跳转到页面
    pageChange(curPage) {
      this.pagging.currentPage = curPage
      this.getTableData()
    },
    // 清除筛选条件
    clearCondition() {
      this.searchForm.area = ''
      this.searchForm.customerName = ''
      this.searchForm.contractId = ''
      this.searchForm.contractName = ''
      this.searchForm.territory = []
      this.searchForm.primaryTerritory = []
      this.searchForm.advancingState = ['是']
      this.searchForm.trackPepole = ''
      this.searchForm.contractDate = ''
      this.searchForm.projectMaturity = []
      this.searchForm.projectLevel = []
      this.searchForm.signType = ''
      this.searchForm.estimatedAmount = null
      this.searchForm.isAdvancingState = ''
      this.searchForm.contractDirection = []
      this.searchForm.isEnable = '是'
      this.search()
    },
    // dailog关闭/取消回调
    onClose() {
      this.getTableData()
    },
    // 新增项目信息
    addProject() {
      Bus.$emit('open-project-dailog', 1, null)
    },
    // 编辑项目信息
    editProject(row) {
      Bus.$emit('open-project-dailog', 2, row.contractId, row.projectMaturity, row.advancingState)
    },
    // 判断跟进提醒
    renderTm(row) {
      if (row.tm && row.advancingState === '是') {
        if (row.projectMaturity === '已签' || row.contractDate === '0001-01-01') {
          return false
        }
        var days = Moment().diff(Moment(row.tm), 'days')
        var newdays = Moment(row.contractDate).diff(Moment(), 'days')
        // console.log(days, newdays)
        if (newdays < 90) {
          if (row.projectLevel === '重点跟进' && days > 7) {
            return true
          }
          if (
            (row.projectLevel === '中等跟进') &&
            days > 15
          ) {
            return true
          }
          if (row.projectLevel === '一般跟进' && days > 30) {
            return true
          }
        }
      }
      return false
    },
    // 判断将到期项目跟踪
    renderProjectLevel(row) {
      var result = false
      if (row.endTime) {
        var days = Moment(row.endTime).diff(Moment(), 'days')
        if (
          row.contractType.indexOf('续保') > -1 &&
          days >= 0 &&
          days < 90
        ) {
          result = true
        }
      }
      return result
    },
    // 初始化下拉菜单
    initEnum() {
      this.options.projectMaturity = this.appEnum.maturity
      this.options.territory = this.options.primaryTerritory = this.appEnum.territory
      this.options.signType = this.appEnum.signType
      this.options.advancingState = this.appEnum.advancingState
      this.options.projectLevel = this.appEnum.projectLevel
      this.options.contractDirection = this.appEnum.direction
      setTimeout(() => {
        if (this.userInfo.department.indexOf('服务') !== -1) this.searchForm.territory.push(this.userInfo.department)
        this.search()
      }, 1000)
    },
    // 导出服务合同盘点表信息
    exprotProjectInfo() {
      this.exprotLoading = true
      const params = _.assignIn({}, this.searchForm, {
        pageIndex: this.pagging.currentPage,
        pageSize: this.pagging.pageSize
      })
      // 多选条件处理
      params.territory = params.territory.join(',')
      params.advancingState = params.advancingState.join(',')
      params.projectMaturity = params.projectMaturity.join(',')
      params.projectLevel = params.projectLevel.join(',')
      params.primaryTerritory = params.primaryTerritory.join(',')
      params.contractDirection = params.contractDirection.join(',')

      if (params.contractDate !== '' && params.contractDate !== null) params.contractDate = Moment(params.contractDate).format('YYYY-MM')

      exprotMInfo(params).then(res => {
        if (res.data.success) {
          window.open('http://' + res.data.data)
        }
      })

      this.exprotLoading = false
    },
    // 显示隐藏说明信息
    onExplain() {
      this.explainDialogVisible = true
    },
    onCloseExplain() {
      this.explainDialogVisible = false
    }
  },
  components: {
    TraceDailog,
    PopoverView,
    Explain
  }
}
</script>
